// DeepSeek API 交互平台 JavaScript 代码
(function() {
    // DOM 元素引用
    const promptTextarea = document.getElementById('prompt');
    const modelSelect = document.getElementById('model');
    const temperatureInput = document.getElementById('temperature');
    const maxTokensInput = document.getElementById('max-tokens');
    const saveToHistoryCheckbox = document.getElementById('save-to-history');
    const clearPromptButton = document.getElementById('clear-prompt');
    const generateResponseButton = document.getElementById('generate-response');
    const fileDropArea = document.getElementById('file-drop-area');
    const fileInput = document.getElementById('file-input');
    const fileInfo = document.getElementById('file-info');
    const fileName = document.getElementById('file-name');
    const removeFileButton = document.getElementById('remove-file');
    const uploadFileButton = document.getElementById('upload-file');
    const downloadResponseButton = document.getElementById('download-response');
    const copyResultButton = document.getElementById('copy-result');
    const clearHistoryButton = document.getElementById('clear-history');
    const loadingModal = document.getElementById('loading-modal');
    const loadingMessage = document.getElementById('loading-message');
    const errorModal = document.getElementById('error-modal');
    const errorMessage = document.getElementById('error-message');
    const closeErrorModal = document.getElementById('close-error-modal');
    const successModal = document.getElementById('success-modal');
    const successMessage = document.getElementById('success-message');
    const closeSuccessModal = document.getElementById('close-success-modal');
    const resultContent = document.getElementById('result-content');
    const historyList = document.getElementById('history-list');
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const mobileMenu = document.getElementById('mobile-menu');
    
    // 禁用下载按钮的函数
    function disableDownloadButton() {
        downloadResponseButton.disabled = true;
        downloadResponseButton.classList.add('text-gray-400');
        downloadResponseButton.classList.remove('text-gray-700');
    }
    
    // 启用下载按钮的函数
    function enableDownloadButton() {
        downloadResponseButton.disabled = false;
        downloadResponseButton.classList.remove('text-gray-400');
        downloadResponseButton.classList.add('text-gray-700');
    }

    // 移动菜单切换
    mobileMenuButton.addEventListener('click', function() {
        mobileMenu.classList.toggle('hidden');
    });

    // 文件上传处理
    // 直接点击上传区域也会触发文件选择

    fileDropArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        fileDropArea.classList.add('border-primary', 'bg-primary/5');
    });

    fileDropArea.addEventListener('dragleave', function() {
        fileDropArea.classList.remove('border-primary', 'bg-primary/5');
    });

    fileDropArea.addEventListener('drop', function(e) {
        e.preventDefault();
        fileDropArea.classList.remove('border-primary', 'bg-primary/5');
        
        if (e.dataTransfer.files.length > 0) {
            handleFileSelection(e.dataTransfer.files[0]);
        }
    });

    fileDropArea.addEventListener('click', function() {
        fileInput.click();
    });

    fileInput.addEventListener('change', function() {
        if (fileInput.files.length > 0) {
            handleFileSelection(fileInput.files[0]);
        }
    });

    function handleFileSelection(file) {
        if (!file.name.endsWith('.md')) {
            showErrorMessage('请上传Markdown格式的文件(.md)');
            return;
        }
        
        fileName.textContent = file.name;
        fileInfo.classList.remove('hidden');
    }

    removeFileButton.addEventListener('click', function() {
        fileInput.value = '';
        fileInfo.classList.add('hidden');
    });

    // 清空提示按钮
    clearPromptButton.addEventListener('click', function() {
        promptTextarea.value = '';
        promptTextarea.focus();
    });

    // 生成回复按钮
    generateResponseButton.addEventListener('click', function() {
        generateResponse();
    });

    // 上传文件按钮
    uploadFileButton.addEventListener('click', function() {
        uploadFile();
    });

    // 下载响应按钮 - 现在是在结果区域的下载按钮
    downloadResponseButton.addEventListener('click', function() {
        if (!downloadResponseButton.disabled) {
            downloadCurrentResponse();
        }
    });

    // 复制结果按钮
    copyResultButton.addEventListener('click', function() {
        copyToClipboard(resultContent.innerText);
        showSuccessMessage('结果已复制到剪贴板');
    });

    // 清空历史按钮
    clearHistoryButton.addEventListener('click', function() {
        if (confirm('确定要清空所有历史记录吗？')) {
            localStorage.removeItem('deepseekHistory');
            renderHistoryList();
            showSuccessMessage('历史记录已清空');
        }
    });

    // 模态框关闭按钮
    closeErrorModal.addEventListener('click', function() {
        errorModal.classList.add('hidden');
    });

    closeSuccessModal.addEventListener('click', function() {
        successModal.classList.add('hidden');
    });

    // API 调用函数
    function generateResponse() {
        const prompt = promptTextarea.value.trim();
        const model = modelSelect.value;
        const temperature = parseFloat(temperatureInput.value);
        const maxTokens = parseInt(maxTokensInput.value);
        
        if (!prompt) {
            showErrorMessage('请输入提示内容');
            promptTextarea.focus();
            return;
        }
        
        showLoading('正在生成回复...');
        
        // 构建请求参数
        const requestData = {
            prompt: prompt,
            model: model,
            temperature: temperature,
            max_tokens: maxTokens
        };
        
        fetch('/api/deepseek/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP 错误! 状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            hideLoading();
            
            if (data.error) {
                showErrorMessage(data.error);
            } else {
                displayResult(data.response);
                
                // 保存到历史记录（总是保存）
                saveToHistory(prompt, data.response);
                
                // 显示复制按钮并启用下载按钮
                copyResultButton.classList.remove('hidden');
                enableDownloadButton();
            }
        })
        .catch(error => {
            hideLoading();
            showErrorMessage(`生成回复失败: ${error.message}`);
        });
    }

    function uploadFile() {
        const file = fileInput.files[0];
        
        if (!file) {
            showErrorMessage('请先选择一个文件');
            return;
        }
        
        showLoading('正在上传并处理文件...');
        
        const formData = new FormData();
        formData.append('file', file);
        
        fetch('/api/deepseek/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            hideLoading();
            
            if (response.ok) {
                response.json().then(data => {
                    if (data.error) {
                        showErrorMessage(data.error);
                    } else {
                        displayResult(data.response);
                        
                        // 保存文件处理结果到历史记录
                        saveToHistory('文件上传: ' + file.name, data.response);
                        
                        copyResultButton.classList.remove('hidden');
                        enableDownloadButton();
                        showSuccessMessage('文件处理完成');
                    }
                });
            } else {
                response.json().then(data => {
                    showErrorMessage(data.error || '文件上传失败');
                });
            }
        })
        .catch(error => {
            hideLoading();
            showErrorMessage(`操作失败: ${error.message}`);
        });
    }

    // 下载当前回复内容为MD文件的函数
    function downloadCurrentResponse() {
        const currentContent = resultContent.innerText;
        
        if (!currentContent || currentContent.includes('DeepSeek 助手随时为您服务') || currentContent.includes('生成的结果将显示在这里')) {
            showErrorMessage('没有可下载的内容');
            return;
        }
        
        showLoading('正在准备下载文件...');
        
        // 构建请求参数
        const requestData = {
            prompt: promptTextarea.value.trim() || 'file_upload',
            response: currentContent,
            model: modelSelect.value,
            temperature: parseFloat(temperatureInput.value),
            max_tokens: parseInt(maxTokensInput.value)
        };
        
        fetch('/api/deepseek/download-response', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        })
        .then(response => {
            hideLoading();
            
            if (response.ok) {
                const contentDisposition = response.headers.get('content-disposition');
                let fileName = 'deepseek-response.md';
                
                if (contentDisposition) {
                    const matches = /filename="([^"]+)"/.exec(contentDisposition);
                    if (matches && matches[1]) {
                        fileName = matches[1];
                    }
                }
                
                response.blob().then(blob => {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                    
                    showSuccessMessage('文件已开始下载');
                });
            } else {
                response.json().then(data => {
                    showErrorMessage(data.error || '下载失败');
                });
            }
        })
        .catch(error => {
            hideLoading();
            showErrorMessage(`下载失败: ${error.message}`);
        });
    }

    // 显示结果函数 - 支持基本的 Markdown 渲染
    function displayResult(text) {
        // 简单的 Markdown 渲染处理
        let formattedText = text;
        
        // 处理标题（#）
        formattedText = formattedText.replace(/^# (.*$)/gm, '<h1 class="text-xl font-bold mb-2">$1</h1>');
        formattedText = formattedText.replace(/^## (.*$)/gm, '<h2 class="text-lg font-bold mb-1">$1</h2>');
        formattedText = formattedText.replace(/^### (.*$)/gm, '<h3 class="text-base font-bold mb-1">$1</h3>');
        
        // 处理无序列表（-）
        formattedText = formattedText.replace(/^- (.*$)/gm, '<li class="list-disc ml-6">$1</li>');
        
        // 处理有序列表（数字.）
        formattedText = formattedText.replace(/^(\d+)\. (.*$)/gm, '<li class="list-decimal ml-6">$2</li>');
        
        // 处理段落
        formattedText = formattedText.replace(/^(?!<h|<li)(.*$)/gm, '<p class="mb-2">$1</p>');
        
        // 处理代码块（```）
        formattedText = formattedText.replace(/```([\s\S]*?)```/g, function(match, code) {
            return '<div class="bg-gray-100 p-4 rounded-lg my-4 overflow-x-auto"><pre><code>' + code + '</code></pre></div>';
        });
        
        // 处理行内代码（`）
        formattedText = formattedText.replace(/`([^`]+)`/g, '<code class="bg-gray-100 px-1 rounded">$1</code>');
        
        // 处理换行符
        formattedText = formattedText.replace(/\n/g, '');
        
        // 替换多个连续的空段落
        formattedText = formattedText.replace(/<p class="mb-2"><\/p>/g, '');
        
        resultContent.innerHTML = formattedText;
    }

    // 历史记录相关函数
    function saveToHistory(prompt, response) {
        const history = getHistory();
        const timestamp = new Date().toISOString();
        
        history.unshift({
            id: timestamp,
            prompt: prompt,
            response: response,
            date: new Date().toLocaleString()
        });
        
        // 限制历史记录数量（最多保存20条）
        if (history.length > 20) {
            history.pop();
        }
        
        localStorage.setItem('deepseekHistory', JSON.stringify(history));
        renderHistoryList();
    }

    function getHistory() {
        const historyJson = localStorage.getItem('deepseekHistory');
        return historyJson ? JSON.parse(historyJson) : [];
    }

    function renderHistoryList() {
        const history = getHistory();
        historyList.innerHTML = '';
        
        if (history.length === 0) {
            const emptyItem = document.createElement('div');
            emptyItem.className = 'text-center text-gray-400 py-6';
            emptyItem.textContent = '暂无历史记录';
            historyList.appendChild(emptyItem);
            return;
        }
        
        history.forEach(item => {
            const historyItem = document.createElement('div');
            historyItem.className = 'p-4 border-b border-gray-100 hover:bg-gray-50 transition-custom cursor-pointer';
            
            // 显示前几行提示内容作为预览
            const promptPreview = item.prompt.substring(0, 100) + (item.prompt.length > 100 ? '...' : '');
            
            historyItem.innerHTML = `
                <div class="text-sm text-gray-500 mb-1">${item.date}</div>
                <div class="text-sm text-gray-700 mb-2">${promptPreview}</div>
                <button class="view-history-item text-primary text-sm hover:underline" data-id="${item.id}">查看详情</button>
            `;
            
            historyList.appendChild(historyItem);
            
            // 添加点击事件
            const viewButton = historyItem.querySelector('.view-history-item');
            viewButton.addEventListener('click', function(e) {
                e.stopPropagation();
                const id = e.target.getAttribute('data-id');
                const historyItem = history.find(item => item.id === id);
                
                if (historyItem) {
                    promptTextarea.value = historyItem.prompt;
                    displayResult(historyItem.response);
                    copyResultButton.classList.remove('hidden');
                    enableDownloadButton();
                    
                    // 滚动到结果区域
                    document.getElementById('result').scrollIntoView({ behavior: 'smooth' });
                }
            });
        });
    }

    // 工具函数
    function copyToClipboard(text) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
    }

    function showLoading(message) {
        loadingMessage.textContent = message;
        loadingModal.classList.remove('hidden');
    }

    function hideLoading() {
        loadingModal.classList.add('hidden');
    }

    function showErrorMessage(message) {
        errorMessage.textContent = message;
        errorModal.classList.remove('hidden');
    }

    function showSuccessMessage(message) {
        successMessage.textContent = message;
        successModal.classList.remove('hidden');
        
        // 2秒后自动关闭成功提示
        setTimeout(function() {
            successModal.classList.add('hidden');
        }, 2000);
    }

    // 初始化
    renderHistoryList();
    disableDownloadButton();
    
    // 默认选中保存到历史记录的复选框
    saveToHistoryCheckbox.checked = true;

    // 平滑滚动处理
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                // 关闭移动菜单（如果打开）
                mobileMenu.classList.add('hidden');
                
                // 滚动到目标元素
                targetElement.scrollIntoView({
                    behavior: 'smooth',
                    block: 'start'
                });
            }
        });
    });

    // 响应式处理
    function handleResize() {
        if (window.innerWidth >= 768) {
            mobileMenu.classList.add('hidden');
        }
    }

    window.addEventListener('resize', handleResize);
    handleResize();
})();